<!--
 * Copyright (c) 2013-Now http://jeesite.com All rights reserved.
 * No deletion without permission, or be held responsible to law.
 * @author PR
-->
<template>
  <BasicTable @register="registerTable">
    <!--  -->
    <!-- :quantity="quantity"  -->

    <template #headerTop v-if="quantity.length > 0" :key="quantityKey">
      <div>
        <Icon :icon="getTitle.icon" class="m-1 pr-1" />
        <span class="fontSize-24 ml-2"> {{ getTitle.value }} </span>
      </div>
      <Nhanalysis
        :quantity="quantity"
        :dlByMoth="dlByMoth"
        :runTime="runTime"
        :avgDl="avgDl"
        :xAxisData="xAxisData"
      />
    </template>
    <!--  -->
    <template #summary>
      <a-table-summary fixed>
        <a-table-summary-row>
          <a-table-summary-cell :index="0" :col-span="1" :style="{ textAlign: 'center' }"
            >合计</a-table-summary-cell
          >
          <a-table-summary-cell :index="1" :col-span="1">&nbsp;</a-table-summary-cell>
          <a-table-summary-cell :index="2" :col-span="1">{{ totalMoney.quantity }}</a-table-summary-cell>
          <a-table-summary-cell :index="3" :col-span="1">&nbsp;</a-table-summary-cell>
          <a-table-summary-cell :index="15" :style="{ textAlign: 'center' }">
            {{ totalMoney.money }}</a-table-summary-cell
          >
        </a-table-summary-row>
      </a-table-summary>
    </template>
  </BasicTable>
</template>
<script lang="ts">
  export default defineComponent({
    name: 'ViewsMesElectrovalenceList',
  });
</script>
<script lang="ts" setup>
  import { defineComponent, ref, computed } from 'vue';
  import Nhanalysis from './Nhanalysis.vue';
  import { useI18n } from '/@/hooks/web/useI18n';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { router } from '/@/router';
  import { BasicTable, BasicColumn, useTable } from '/@/components/Table';
  import { listDlData } from '/@/api/mes/electrovalence/mesScElectrovalence';
  import { devListDlData } from '/@/api/mes/card/mesDev';
  import { FormProps } from '/@/components/Form';
  import { Icon } from '/@/components/Icon';
  import { dateUtil } from '/@/utils/dateUtil';

  const { t } = useI18n('card.kstMesProCardData');
  const { showMessage } = useMessage();
  const getTitle = {
    icon: router.currentRoute.value.meta.icon || 'ant-design:book-outlined',
    value: router.currentRoute.value.query.code,
  };
  const quantity = ref([]);
  const xAxisData = ref([]);
  const quantityKey = computed(() => JSON.stringify(quantity.value));
  const params = ref({});
  const dlByMoth = ref(0);
  const runTime = ref(0);
  const avgDl = ref(0);
  const startTimeStr = ref('');
  const endTimeStr = ref('');

  const searchForm: FormProps = {
    baseColProps: { lg: 7, md: 12 },
    labelWidth: 90,
    autoAdvancedLine: 4,
    schemas: [
      {
        label: t('时间'),
        field: 'date',
        component: 'DatePicker',
        componentProps: {
          format: 'YYYY-MM-DD',
          valueFormat: 'YYYY-MM-DD',
          defaultValue: dateUtil(new Date()).format('YYYY-MM-DD'),
        },
      },
    ],
  };

  const tableColumns: BasicColumn[] = [
    // createBy
    {
      title: t('时间段'),
      dataIndex: 'hourBetween',
      key: 'a.hour_between',
      sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('能耗（度）'),
      dataIndex: 'quantity',
      key: 'a.quantity',
      // sorter: true,
      width: 130,
      align: 'left',
    },
    {
      title: t('单价（元/度）'),
      dataIndex: 'price',
      key: 'a.price',
      sorter: true,
      width: 130,
      align: 'center',
    },
    {
      title: t('总价（元）'),
      dataIndex: 'money',
      key: 'a.money',
      sorter: true,
      width: 130,
      align: 'center',
    },
  ];

  const [registerTable, { reload, getForm, getRawDataSource, getDataSource }] = useTable({
    api: devListDlData,
    beforeFetch: (params) => {
      params.date = params.date ? params.date : dateUtil(new Date()).format('YYYY-MM-DD');
      params.ceqcode = router.currentRoute.value.query.code;
      params.ceqname = router.currentRoute.value.query.code;
      return params;
    },
    afterFetch: (res) => {
      // data.value = getRawDataSource().data;
      // res 为数组，把数组里面的每一个对象的quantity 单独拿出去，放在一个data数组里面
      if (res.length == 0) {
        quantity.value = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
      } else {
        quantity.value = res.map((item) => item.quantity);
        // 过滤掉quantity 为0的数据
        // quantity.value = quantity.value.filter(item => item != 0);
        // xAxisData.value = res.filter(item => item.quantity != 0).map( item => item.hour);
        // xAxisData.value = res.map( item => item.hour+':00')
        // console.log('xAxisData.value', xAxisData.value);
      }
      // xAxisData.value = res.map( item => item.hourBetween);

      const paramsValue = getForm().getFieldsValue();
      res.forEach((item) => {
        item.ceqcode = paramsValue.ceqcode;
        item.ceqname = paramsValue.ceqname;
      });
      dlByMoth.value = getRawDataSource().otherData.dlByMoth;
      runTime.value = getRawDataSource().otherData.runTime;
      avgDl.value = getRawDataSource().otherData.avgDl;
      startTimeStr.value = getRawDataSource().otherData.startTimeStr;
      endTimeStr.value = getRawDataSource().otherData.endTimeStr;
      // 遍历res 如果第一个 item.quantity 大于 0 ，把 对应的 index 的 hour 替换成 startTimeStr.value 
      //  最后一个 item.quantity 大于 0 ，把对应的 index 的 hour 替换成 endTimeStr.value
      const startTimeStrIndex = res.findIndex((item) => item.quantity > 0);
      const endTimeStrIndex = res.findLastIndex((item) => item.quantity > 0);
      xAxisData.value = res.map((item, index) => {
        if (index === startTimeStrIndex - 1) {
          item.hour = startTimeStr.value;
        }
        if (index === startTimeStrIndex) {
          item.hour = '';
        }
        if (index === endTimeStrIndex + 1) {
          item.hour = endTimeStr.value;
        }
        if (index === endTimeStrIndex) {
          item.hour = '';
        }
        console.log('item', item.hour);
        return item.hour;
      });
    },
    columns: tableColumns,
    // actionColumn: actionColumn,
    formConfig: searchForm,
    showTableSetting: true,
    useSearchForm: true,
    canResize: true,
    pagination: false,
  });

  function handleSuccess() {
    reload();
  }

  // 计算总报工数
  const totalMoney = computed(() => {
    // 计算总报工数
    const tableData = getDataSource();
    // const tableData = getDataSource.value;
    let sum = tableData.reduce((total, item) => total + (item.money || 0), 0);
    let sumQuantity = tableData.reduce((total, item) => total + (item.quantity || 0), 0);
    return {
      money: Number(sum.toFixed(2)),
      quantity: Number(sumQuantity.toFixed(2))
    };
  });
</script>
<style lang="less" scoped>
  .fontSize-24 {
    font-size: 24px !important;
    font-weight: bold !important;
  }
</style>
